<template>
    <view class="llx-container">
        <scroll-view 
            class="list" 
            :scroll-y="true" 
            @scrolltolower="loadMorePolicies"
            :refresher-enabled="true" 
            :refresher-triggered="refresherTriggered" 
            @refresherrefresh="onRefresherRefresh" 
            refresher-background="#f5f5f5"
        >
            <view class="card life-tips">
                <view class="card-header">
                    <image :src="IMAGE_URL + '/static/community/icon13.png'" style="width: 32rpx; height: 24rpx;"></image>
                    <text class="title">生活小贴士</text>
                </view>
                <view class="marquee-rows">
                    <view class="marquee-row">
                        <view class="marquee-track" :style="{ animationDuration: row1Speed + 's' }">
                            <view class="group">
                                <view class="tag" v-for="(tag, idx) in row1ShownTags" :key="idx" @click="gotoUrl('/views/community/life-tips?id=' + tag.id)">
                                    <text>{{ tag.title }}</text>
                                    <span class="iconfont icon-dengpaotishi"></span>
                                </view>
                            </view>
                            <view class="group">
                                <view class="tag" v-for="(tag, idx) in row1ShownTags" :key="idx" @click="gotoUrl('/views/community/life-tips?id=' + tag.id)">
                                    <text>{{ tag.title }}</text>
                                    <span class="iconfont icon-dengpaotishi"></span>
                                </view>
                            </view>
                        </view>
                    </view>
                    <view class="marquee-row">
                        <view class="marquee-track" :style="{ animationDuration: row2Speed + 's' }">
                            <view class="group">
                                <view class="tag" v-for="(tag, idx) in row2ShownTags" :key="idx" @click="gotoUrl('/views/community/life-tips?id=' + tag.id)">
                                    <text>{{ tag.title }}</text>
                                    <span class="iconfont icon-dengpaotishi"></span>
                                </view>
                            </view>
                            <view class="group">
                                <view class="tag" v-for="(tag, idx) in row2ShownTags" :key="idx" @click="gotoUrl('/views/community/life-tips?id=' + tag.id)">
                                    <text>{{ tag.title }}</text>
                                    <span class="iconfont icon-dengpaotishi"></span>
                                </view>
                            </view>
                        </view>
                    </view>
                </view>
            </view>

            <view class="box-con">
                <!-- 热门话题 -->
                <view class="card section" @click="gotoUrl('/views/community/topic-square')">
                    <!-- 装饰图标 -->
                    <image class="section-icon" :src="IMAGE_URL + '/static/community/icon15.png'" mode="aspectFit"></image>
                    
                    <view class="section-header">
                        <span class="iconfont icon-remen icon"></span>
                        <text class="section-title">热门话题</text>
                    </view>
                    <view class="topic-list">
                        <view class="topic-item" v-for="(t, i) in hotTopics" :key="i" @click.stop="gotoUrl('/views/community/topic-square-detail?id=' + t.id)">
                            <view class="txt-lt">
                                <text class="index">{{ i + 1 }}.</text>
                                <text class="text">{{ t.title }}</text>
                            </view>
                            <view class="txt-lr">
                                <span class="iconfont icon-mn_hudong"></span>
                                <text class="hd-num">{{ t.comment_count }}互动</text>
                            </view>
                        </view>
                    </view>
                </view>

                <!-- 社区通知 -->
                <view class="card section sq"  @click="gotoUrl('/views/community/notice')">
                    <!-- 装饰图标 -->
                    <image class="section-icon sq-icon" :src="IMAGE_URL + '/static/community/icon14.png'" mode="aspectFit"></image>
                    
                    <view class="section-header">
                        <span class="iconfont icon-tongzhi icon"></span>
                        <text class="section-title">社区通知</text>
                    </view>
                    <view class="notice-list">
                        <view class="notice-item" v-for="(n, i) in communityNotices" :key="i" @click.stop="gotoUrl('/views/community/notice-detail?id=' + n.id)">
                            <text class="date">{{ n.create_time }}</text>
                            <text class="text">{{ n.title }}</text>
                        </view>
                    </view>
                </view>

                <!-- 政策解读 -->
                <view class="policy-block">
                    <view class="policy-title">
                        <view class="tit-bg">UNSCRAMBLE</view>
                        <text class="tit">政策解读</text>
                    </view>
                    <view class="card policy-card" v-for="(p, i) in policies" :key="i" @click.stop="gotoUrl('/views/community/policy-detail?id=' + p.id)">
                        <view class="policy-item">
                            <view class="policy-name">{{ p.title }}</view>
                            <view class="policy-text">
                                <view class="policy-text-lr">
                                    <view class="policy-desc">
                                        <view class="policy-desc-inner">
                                            <u-parse :content="p.content"></u-parse>
                                        </view>
                                        <view v-if="overflowPolicyFlags[i]" class="policy-ellipsis-overlay">...</view>
                                    </view>
                                    <view class="policy-meta">
                                        <view class="policy-meta-user">
                                            <image :src="p.pic" style="width: 28rpx; height: 28rpx;"></image>
                                            <text class="name">{{ p.author }}</text>
                                        </view>
                                        <text class="time">{{ p.create_time }}发布</text>
                                    </view>
                                </view>
                                <image :src="p.image_url" mode="aspectFill" class="policy-thumb" />
                            </view>
                        </view>
                    </view>
                    <view class="list-footer">
                        <text v-if="policyLoading">正在加载...</text>
                        <text v-else-if="!policyHasMore">已经加载全部</text>
                    </view>
                </view>
            </view>
        </scroll-view>
    </view>
</template>
<script>
import { getCommunitynewsLifetipList, getCommunitynewsTopicHot,getCommunitynewsNoticeList,getCommunitynewsPolicyList } from '@/api/index.js'
import appConfig from '@/config/app.js'
export default {
    data() {
        return {
            IMAGE_URL: appConfig.IMAGE_URL,
            row1Tags: [],
            row2Tags: ['夏季防暑指南', '科学护眼', '合理膳食搭配', '规律作息', '家庭急救小常识'],
            // 用于展示的扩展数组，避免数据过少导致滚动空白
            row1ShownTags: [],
            row2ShownTags: [],
            row1Speed: 18,
            row2Speed: 20,
            hotTopics: [],
            communityNotices: [],
            policies: [],
            // 政策分页
            policyPage: 1,
            policyLimit: 10,
            policyHasMore: true,
            policyLoading: false,
            // 下拉刷新相关
            refresherTriggered: false,
            lastRefreshTime: 0,
            refreshDebounceTime: 2000,
            // 溢出标记（政策解读）
            overflowPolicyFlags: [],
            // 溢出检测重试
            overflowPolicyRetry: 0,
            overflowPolicyTimer: null
        }
    },
    mounted() {
        this.init()
        this.$on('search', (keyword) => {
            this.doSearch(keyword)
        })
    },
    onReady() {
        // App 端 u-parse 渲染存在异步，初次进入再测一次
        this.$nextTick(() => {
            this.checkPolicyOverflow(true)
        })
    },
    methods: {
        doSearch(keyword){
            this.gotoUrl('/views/community/topic-square?keyword=' + keyword)
        },
        onRefresherRefresh() {
            // 防止重复触发刷新或在加载中再次刷新
            if (this.policyLoading || this.refresherTriggered) {
                return
            }
            
            this.refresherTriggered = true
            this.init()
        },
        init() {
            // 重置所有状态
            this.policyPage = 1
            this.policyHasMore = true
            this.policies = []
            
            // 并行加载所有数据
            Promise.all([
                this.getCommunitynewsLifetipListEvent(),
                this.getCommunitynewsTopicHotEvent(),
                this.getCommunitynewsNoticeListEvent(),
                this.getCommunitynewsPolicyListEvent()
            ]).finally(() => {
                this.refresherTriggered = false
                this.$nextTick(() => {
                    this.checkPolicyOverflow()
                })
            })
        },
        gotoUrl(url) {
            uni.navigateTo({
                url:url
            })
        },
        async getCommunitynewsLifetipListEvent() {
            const res = await getCommunitynewsLifetipList({page:1, limit: 999});
            const half = Math.ceil(res.data.list.length / 2)
            this.row1Tags = res.data.list.slice(0, half)
            this.row2Tags = res.data.list.slice(half)
            this.hydrateMarqueeArrays()
            this.updateMarqueeSpeed()
        },
        hydrateMarqueeArrays() {
            // 根据容器和tag的平均宽度估算至少需要多少个标签以无缝滚动
            // 这里简单设置最小数量阈值，实际可按屏宽/单个tag宽动态计算
            const MIN_TAGS = 8
            const expandTo = (arr) => {
                const out = [...arr]
                if (out.length === 0) return out
                while (out.length < MIN_TAGS) {
                    // 复制自身直至达到阈值，避免出现空白
                    out.push(...arr)
                }
                return out.slice(0, Math.max(out.length, MIN_TAGS))
            }
            this.row1ShownTags = expandTo(this.row1Tags)
            this.row2ShownTags = expandTo(this.row2Tags)
        },

        // 依据可视标签数量计算动画时长，确保滚动速度（px/s）基本一致
        updateMarqueeSpeed() {
            // 每个标签的基准时长（秒），可按视觉调优
            const BASE_SEC_PER_TAG = 4.2
            const clamp = (v, min, max) => Math.max(min, Math.min(max, v))
            const len1 = (this.row1ShownTags && this.row1ShownTags.length) ? this.row1ShownTags.length : 0
            const len2 = (this.row2ShownTags && this.row2ShownTags.length) ? this.row2ShownTags.length : 0
            // 给一个合理的范围，避免时间过短或过长
            this.row1Speed = clamp(len1 * BASE_SEC_PER_TAG, 12, 60)
            this.row2Speed = clamp(len2 * BASE_SEC_PER_TAG, 12, 60)
        },
        async getCommunitynewsTopicHotEvent() {
            const res = await getCommunitynewsTopicHot({page:1, limit: 3})
            this.hotTopics = res.data
        },
        async getCommunitynewsNoticeListEvent() {
            const res = await getCommunitynewsNoticeList({page:1, limit: 3})
            res.data.list.map(item => item.create_time = item.create_time.split(' ')[0])
            this.communityNotices = res.data.list
        },
        async getCommunitynewsPolicyListEvent() {
            if (this.policyLoading || !this.policyHasMore) return
            this.policyLoading = true
            try {
                const res = await getCommunitynewsPolicyList({
                    page: this.policyPage,
                    limit: this.policyLimit
                })
                const list = (res && res.data && res.data.list) ? res.data.list : []
                if (this.policyPage === 1) {
                    this.policies = list
                } else {
                    this.policies = this.policies.concat(list)
                }
                // 判断是否还有更多
                if (list.length < this.policyLimit) {
                    this.policyHasMore = false
                } else {
                    this.policyPage += 1
                }
                // 等待 u-parse 完成渲染后再测量，必要时重试
                this.$nextTick(() => {
                    this.checkPolicyOverflow(true)
                })
            } catch (err) {
                if (this.refresherTriggered) {
                    uni.showToast({
                        title: '网络错误，请检查网络连接',
                        icon: 'none',
                        duration: 2000
                    })
                }
            } finally {
                this.policyLoading = false
            }
        },
        loadMorePolicies() {
            if (this.policyLoading) return
            if (!this.policyHasMore) {
                uni.showToast({ title: '已经加载完全部了', icon: 'none' })
                return
            }
            this.getCommunitynewsPolicyListEvent()
        },
        // 检测政策解读富文本是否超过 120rpx（带重试）
        checkPolicyOverflow(force = false) {
            if (force) {
                this.overflowPolicyRetry = 0
            }
            const query = uni.createSelectorQuery().in(this)
            query.selectAll('.policy-desc-inner').boundingClientRect(rects => {
                const limitPx = uni.upx2px(110)
                // 若未渲染好或高度为 0，延迟重试（最多 5 次）
                const needRetry = !rects || !rects.length || rects.some(r => !r || !r.height)
                if (needRetry && this.overflowPolicyRetry < 5) {
                    this.overflowPolicyRetry += 1
                    if (this.overflowPolicyTimer) clearTimeout(this.overflowPolicyTimer)
                    this.overflowPolicyTimer = setTimeout(() => {
                        this.checkPolicyOverflow()
                    }, 120)
                    return
                }
                const flags = (rects || []).map(r => (r && r.height) ? r.height > limitPx : false)
                // 若列表长度与测量不一致，补齐/截断
                const len = this.policies ? this.policies.length : 0
                this.overflowPolicyFlags = flags.length === len ? flags : Array.from({length: len}, (_, i) => !!flags[i])
                // 成功后重置重试计数
                this.overflowPolicyRetry = 0
            }).exec()
        }
    }

}
</script>
<style lang="scss" scoped>
.llx-container {
    width: 100%;
    height: 100%;

    .list {
        height: 100%;
    }
}

.box-con {
    padding: 0 32rpx;
}

.card {
    margin: 16rpx 0 0;
    border-radius: 16rpx;
}

.card-header {
    display: flex;
    align-items: center;
    margin: 0 0 0 32rpx;
}

.card-header .title {
    font-size: 30rpx;
    font-weight: 600;
    color: #333;
    margin-left: 4rpx;
}

/* 两行不间断左向滚动 */
.marquee-rows {
    display: flex;
    flex-direction: column;
}

.marquee-row {
    overflow: hidden;
    margin-top: 28rpx;
}

.marquee-track {
    display: inline-flex;
    width: max-content;
    animation-name: marqueeLeft;
    animation-timing-function: linear;
    animation-iteration-count: infinite;
}

.group {
    display: inline-flex;
}

.tag {
    position: relative;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    box-shadow: 0rpx 4rpx 12rpx 0rpx rgba(0,0,0,0.08);
    border-radius: 12rpx;
    padding: 12rpx 20rpx;
    background: #FFFFFF;
    color: #666;
    font-size: 24rpx;
    margin-right: 40rpx;

    .icon-dengpaotishi {
        color: #DF9824;
        margin-left: 10rpx;
        font-size: 30rpx;
    }
}

.tag-icon {
    position: absolute;
    right: 10rpx;
}

@keyframes marqueeLeft {
    from {
        transform: translateX(0);
    }

    to {
        transform: translateX(-50%);
    }
}

/* section blocks */
.section {
    position: relative;
    height: 288rpx;
    margin: 28rpx 0;
    background: linear-gradient( 180deg, #FFFBF4 0%, #FFFFFF 20%);
    box-shadow: 0rpx 4rpx 20rpx 0rpx rgba(0,0,0,0.1);
    border-radius: 20rpx 20rpx 20rpx 20rpx;

    &.sq {
        background: linear-gradient( 180deg, #F2FAFF 0%, #FFFFFF 20%);
    }
}

.section-icon {
    position: absolute;
    width: 172rpx;
    height: 96rpx;
    top: 0;
    right: -17rpx;
    pointer-events: none;
    z-index: 1;

    &.sq-icon {
        top: -15rpx;
    }
}

.section-header {
    display: flex;
    align-items: center;
    padding: 28rpx;
}

.section-title {
    font-size: 28rpx;
    font-weight: 600;
    color: #333;
}

.icon {
    margin-right: 10rpx;
    font-size: 30rpx;
}

.icon-remen {
    color: #DF9824;
}

.icon-tongzhi {
    color: #0785CF;
}

.topic-list {
    padding: 0 28rpx;
}

.topic-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin:0 0 20rpx;

    .txt-lt {
        width: 450rpx;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
    }

    .txt-lr {
        .icon-mn_hudong {
            margin-right: 5rpx;
        }

        .hd-num,
        .icon-mn_hudong {
            font-size: 24rpx;
            color: #FF4D4D;
        }
    }
}

.topic-item .index {
    font-size: 28rpx;
    color: #333333;
    text-align: right;
    margin-right: 8rpx;
}

.topic-item .text {
    color: #333;
    font-size: 26rpx;
}

.notice-list {
    padding: 0 28rpx;
}

.notice-item {
    display: flex;
    margin: 0 0 20rpx;
    color: #333;
    font-size: 28rpx;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.notice-item .date {
    color: #333;
    margin-right: 5rpx;
    white-space: nowrap;
}

/* policy */
.policy-block {
    margin: 24rpx 0;
}

.policy-title {
    position: relative;
    text-align: center;
    font-weight: 700;
    color: #333;
    margin: 16rpx 0;
    font-size: 36rpx;

    .tit-bg {
        position: absolute;
        left: 50%;
        transform: translateX(-50%);
        top: 0;
        font-weight: 800;
        font-size: 48rpx;
        color: rgba(7,133,207,0.08);
    }

    .tit {
        line-height: 2.5;
    }
}

.policy-card {
    padding: 0;
    height: 274rpx;
    background: #FFFFFF;
    box-shadow: 0rpx 4rpx 20rpx 0rpx rgba(0,0,0,0.1);
    border-radius: 20rpx 20rpx 20rpx 20rpx;
}

.policy-item {
    padding: 28rpx;
}

.policy-text {
    display: flex;
    justify-content: space-between;
    align-items: center;

    &-lr {
        width: 442rpx;
        height: 160rpx;
        text-align: justify;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
    }
}

.policy-name {
    font-size: 28rpx;
    color: #333;
    font-weight: 600;
    margin-bottom: 8rpx;
}

.policy-desc {
    font-size: 24rpx;
    color: #666;
    line-height: 1.6;
    overflow: hidden;
    max-height: 110rpx;
    position: relative;
}

.policy-ellipsis-overlay {
    position: absolute;
    right: 0;
    bottom: 0;
    padding-left: 6rpx;
    background: #FFFFFF;
    color: #666;
}

.policy-meta {
    font-size: 22rpx;
    color: #999;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .policy-meta-user {
        display: flex;
        align-items: center;

        .name {
            margin-left: 5rpx;
        }
    }
}

.policy-thumb {
    width: 160rpx;
    height: 160rpx;
    border-radius: 8rpx;
}

.list-footer {
    padding: 20rpx 0 40rpx;
    text-align: center;
    color: #999;
    font-size: 24rpx;
}
</style>